package com.tgpms.web.earlierStage.controller;

import com.tgpms.auth.security.TokenService;
import com.tgpms.common.Result;
import com.tgpms.exception.ExceptionExplain;
import com.tgpms.exception.InsertException;
import com.tgpms.util.Common;
import com.tgpms.web.earlierStage.entity.ProjectInfo;
import com.tgpms.web.earlierStage.entity.TaskDefinition;
import com.tgpms.web.earlierStage.entity.TaskJournal;
import com.tgpms.web.earlierStage.service.EarlierProjectInfoService;
import com.tgpms.web.earlierStage.service.EarlierTaskDefinService;
import com.tgpms.web.earlierStage.service.EarlierTaskJouService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "EarlierTaskDefinController", tags = "前期 任务分解相关接口")
@RestController
@RequestMapping(value = "/ev/earlierTaskDefin")
public class EarlierTaskDefinController {

	@Autowired
	private EarlierProjectInfoService earlierProjectInfoService;
	@Autowired
	private EarlierTaskDefinService earlierTaskDefinService;
	@Autowired
	private EarlierTaskJouService earlierTaskJouService;
	@Autowired
	private TokenService tokenService;

	@ApiOperation(value = "新增任务分解接口", notes = "新增任务分解接口", httpMethod = "POST")
	@PostMapping(value = "/addTaskDefin")
	public Result addTaskDefin(@RequestBody TaskDefinition taskDefin, HttpServletRequest request) {
		Result result = new Result();
		try {
			if(taskDefin.getPlanStartDate()!=null && taskDefin.getPlanEndDate()!=null) {
				if(taskDefin.getPlanStartDate().compareTo(taskDefin.getPlanEndDate())>=0) {
					result.setSuccess(false);
					result.setMsg("计划任务开始时间必须早于任务结束时间");
					return result;
				}
			}
			String insertName = tokenService.getUserName(request);
			taskDefin.setInsertUser(insertName);
			result = earlierTaskDefinService.addTaskDefin(taskDefin, result);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_INSERT.getExplain());
			throw new InsertException(ExceptionExplain.ERROR_BY_INSERT.getExplain());
		}
		return result;
	}


	@ApiOperation(value = "修改任务分解接口", notes = "修改任务分解接口", httpMethod = "PUT")
	@PutMapping(value = "/updateTaskDefin")
	public Result updateTaskDefin(@RequestBody TaskDefinition taskDefin, HttpServletRequest request) {
		Result result = new Result();
		if (Common.isEmpty(taskDefin.getId())) {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.EMPTY_BY_DATA.getExplain() + "|主键为空");
			return result;
		}
		if(taskDefin.getPlanStartDate()!=null && taskDefin.getPlanEndDate()!=null) {
			if(taskDefin.getPlanStartDate().compareTo(taskDefin.getPlanEndDate())>=0) {
				result.setSuccess(false);
				result.setMsg("计划任务开始时间必须早于任务结束时间");
				return result;
			}
		}
		if(taskDefin.getActulStartDate()!=null && taskDefin.getActulEndDate()!=null) {
			if(taskDefin.getActulStartDate().compareTo(taskDefin.getActulEndDate())>=0) {
				result.setSuccess(false);
				result.setMsg("实际任务开始时间必须早于实际结束时间");
				return result;
			}
		}
		try {
			String insertName = tokenService.getUserName(request);
			taskDefin.setModifyUser(insertName);
			result = earlierTaskDefinService.updateTaskDefin(taskDefin, result);
			//异步执行
			new Thread() {
				public void run() {
					//判断是否修改任务的无需办理状态，改变状态则重新计算上级百分比
					if (taskDefin.getIfIgnore() != null && taskDefin.getIfIgnore().equals("1")) {
						TaskJournal taskJou = new TaskJournal();
						taskJou.setId(taskDefin.getId());
						earlierTaskJouService.countPercent(taskJou, 2);
					}
				}
			}.start();

		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
			throw new InsertException(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
		}
		return result;
	}

	@ApiOperation(value = "删除任务分解接口", notes = "删除任务分解接口", httpMethod = "DELETE")
	@DeleteMapping(value = "/deleteTaskDefin")
	public Result deleteTaskDefin(@RequestParam(value = "id", required = true) String id, HttpServletRequest request) {
		Result result = new Result();
		if (Common.isEmpty(id)) {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.EMPTY_BY_DATA.getExplain() + "|主键为空");
			return result;
		}
		try {
			result = earlierTaskDefinService.deleteTaskDefin(id, result);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_DELETE.getExplain());
			throw new InsertException(ExceptionExplain.ERROR_BY_DELETE.getExplain());
		}
		return result;
	}


	@ApiOperation(value = "查询任务分解树形接口", notes = "查询任务分解树形接口", httpMethod = "POST")
	@PostMapping(value = "/selTaskDefinitionForTree")
	public Result selTaskDefinitionForTree(@RequestParam(value = "id", required = false) String id,
			@RequestParam(value = "projectId", required = false) String projectId) {
		Result result = new Result();
		try {
			List<Object> list = earlierTaskDefinService.selTaskDefin(id, projectId);
			result.setMsg(ExceptionExplain.SUCCESS_BY_INFOS.getExplain());
			result.setData(list);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_QUERY.getExplain());
			throw new InsertException(ExceptionExplain.ERROR_BY_QUERY.getExplain());
		}
		return result;
	}


	@ApiOperation(value = "查询任务分解异步加载接口", notes = "查询任务分解异步加载接口", httpMethod = "POST")
	@PostMapping(value = "/selTaskDefinitionByArs")
	public Result selTaskDefinitionByArs(@RequestParam(value = "id", required = false) String id,
			@RequestParam(value = "projectId", required = false) String projectId) {
		Result result = new Result();
		if (Common.isEmpty(projectId)) {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.EMPTY_BY_DATA.getExplain());
			return result;
		}
		try {
			List<Object> list = earlierTaskDefinService.selTaskDefinByArs(id, projectId);
			result.setMsg(ExceptionExplain.SUCCESS_BY_INFOS.getExplain());
			result.setData(list);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_QUERY.getExplain());
			throw new InsertException(ExceptionExplain.ERROR_BY_QUERY.getExplain());
		}
		return result;
	}


	@ApiOperation(value = "任务模板导入接口", notes = "任务模板导入接口", httpMethod = "POST")
	@PostMapping(value = "/taskTempImport")
	public Result taskTempImport(@RequestParam(value = "listStr", required = false) String listStr,
			@RequestParam(value = "projectId", required = false) String projectId, HttpServletRequest request) {
		Result result = new Result();
		if (Common.isEmpty(listStr) || Common.isEmpty(projectId) || listStr.equals("[]")) {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.EMPTY_BY_DATA.getExplain());
			return result;
		}
		try {
			String insertName = tokenService.getUserName(request);
			result = earlierTaskDefinService.taskTempImport(listStr, projectId, insertName, result);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_QUERY.getExplain());
			throw new InsertException(ExceptionExplain.ERROR_BY_QUERY.getExplain());
		}
		return result;
	}

	@ApiOperation(value = "发布任务接口POST请求", notes = "发布任务接口POST请求", httpMethod = "POST")
	@PostMapping(value = "/launchTask")
	public Result launchTask(@RequestParam(value = "id", required = false) String id, HttpServletRequest request) {
		Result result = new Result();
		if (Common.isEmpty(id)) {
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.EMPTY_BY_DATA.getExplain());
			return result;
		}
		try {
			String modifyUser = tokenService.getUserName(request);
			result = earlierTaskDefinService.launchTask(id, modifyUser);
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
			throw new InsertException(ExceptionExplain.ERROR_BY_UPDATE.getExplain());
		}
		return result;
	}

	@ApiOperation(value = "工程项目进度表", notes = "工程项目进度表", httpMethod = "POST")
	@RequestMapping(value = "/projectReport", produces= MediaType.APPLICATION_OCTET_STREAM_VALUE)
	public void projectReport(@RequestParam(value = "projectId", required = false) String projectId,
			HttpServletResponse response) throws IOException {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("工程项目进度表");
		String fileName = "工程项目进度表";

		Map<String, Object> map = new HashMap<>();

		// 创建合并的单元格
		CellRangeAddress cra1 = new CellRangeAddress(0, 0, 1, 5);
		CellRangeAddress cra2 = new CellRangeAddress(1, 1, 1, 5);
		CellRangeAddress cra3 = new CellRangeAddress(2, 2, 1, 2);
		CellRangeAddress cra4 = new CellRangeAddress(2, 2, 4, 5);
		CellRangeAddress cra5 = new CellRangeAddress(3, 3, 1, 2);
		CellRangeAddress cra6 = new CellRangeAddress(3, 3, 4, 5);
		CellRangeAddress cra7 = new CellRangeAddress(4, 4, 0, 5);
		sheet.addMergedRegion(cra1);
		sheet.addMergedRegion(cra2);
		sheet.addMergedRegion(cra3);
		sheet.addMergedRegion(cra4);
		sheet.addMergedRegion(cra5);
		sheet.addMergedRegion(cra6);
		sheet.addMergedRegion(cra7);

		ProjectInfo projectInfo = earlierProjectInfoService.selProjectInfoByCondition(projectId);

		HSSFRow row1 = sheet.createRow(0);
		row1.createCell(0).setCellValue("工程名称");
		row1.createCell(1).setCellValue(projectInfo.getObsProjectName());

		HSSFRow row2 = sheet.createRow(1);
		row2.createCell(0).setCellValue("项目地址");
		row2.createCell(1).setCellValue(projectInfo.getProjectAddress());

		HSSFRow row3 = sheet.createRow(2);
		row3.createCell(0).setCellValue("项目估算投资");
		if (projectInfo.getEstimatedInvestment() != null) {
			row3.createCell(1).setCellValue(projectInfo.getEstimatedInvestment().toString());
		}
		row3.createCell(3).setCellValue("项目负责人");
		row3.createCell(4).setCellValue(projectInfo.getProjectResp());

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		HSSFRow row4 = sheet.createRow(3);
		row4.createCell(0).setCellValue("计划开工日期");
		row4.createCell(1).setCellValue(sdf.format(projectInfo.getPlanStartDate()));
		row4.createCell(3).setCellValue("计划竣工日期");
		row4.createCell(4).setCellValue(sdf.format(projectInfo.getPlanStartDate()));

		sheet.createRow(4).createCell(0).setCellValue("前期工作进度展示");

		// 在excel表中添加表头
		String[] headers = {"序号", "工作流程", "子工作流程", "状态", "完成日期", "进度"};
		HSSFRow row5 = sheet.createRow(5);
		for (int i = 0; i < headers.length; i++) {
			HSSFCell cell = row5.createCell(i);
			cell.setCellValue(headers[i]);
		}
		//		PoiUtil.getExcelHeaders(sheet, 5, headers);

		int rowNum = 6;
		map.put("projectId", projectId);
		List<Map<String, Object>> lists = earlierTaskDefinService.selReportTable(map);
		for (Map<String, Object> temp : lists) {
			HSSFRow ro = sheet.createRow(rowNum);
			// 循环遍历键并赋值
			ro.createCell(0).setCellValue(temp.get("ORDER_NO").toString());
			ro.createCell(1).setCellValue(temp.get("PARENT_NAME").toString());
			ro.createCell(2).setCellValue(temp.get("TASK_DESC").toString());
			if (temp.get("NODE_STATUS") != null) {
				ro.createCell(3).setCellValue(temp.get("NODE_STATUS").toString());
			} else {
				ro.createCell(3).setCellValue("");
			}
			if (temp.get("END_DATE") != null) {
				ro.createCell(4).setCellValue(temp.get("END_DATE").toString());
			} else {
				ro.createCell(4).setCellValue("");
			}
			if (temp.get("PROCESS") != null) {
				ro.createCell(5).setCellValue(temp.get("PROCESS").toString());
			} else {
				ro.createCell(5).setCellValue("");
			}
			rowNum++;
		}

		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "utf-8"));
		response.setHeader("FileName", URLEncoder.encode(fileName, "utf-8"));
		response.setHeader("Access-Control-Expose-Headers", "FileName");

		OutputStream os = response.getOutputStream();
		workbook.write(os);
		os.close();
	}

	//	@PostMapping(value = "/lixiang")
	//	public void lixiang(HttpServletRequest request) {
	//		earlierTaskDefinService.lixiang();
	//	}

}
